// src/utils/api.ts - 纯前端Mock版本
import type { Station } from '@/types/station'

// 模拟网络延迟
const simulateNetworkDelay = () => new Promise(resolve => 
  setTimeout(resolve, Math.random() * 500 + 200)
)

// 从public/mockStations.json加载数据
export const fetchStations = async (): Promise<Station[]> => {
  await simulateNetworkDelay()
  
  try {
    const response = await fetch('/mockStations.json')
    const data = await response.json()
    return data.stationList
  } catch (error) {
    console.error('加载充电站数据失败:', error)
    // 回退到本地mock数据
    return (await import('./mockData')).mockStationsNew
  }
}

// 模拟状态更新 - 纯前端逻辑
export const updateStationStatus = async (stationId: string): Promise<boolean> => {
  await simulateNetworkDelay()
  
  // 模拟90%的成功率，10%模拟失败情况
  const success = Math.random() > 0.1
  
  if (!success) {
    console.warn(`模拟API调用失败: 更新充电站 ${stationId}`)
  }
  
  return success
}

// 模拟WebSocket连接 - 纯前端轮询
export const createMockWebSocket = (onUpdate: (data: any) => void) => {
  let intervalId: number
  
  const start = () => {
    intervalId = window.setInterval(() => {
      // 每5秒随机更新一个充电站状态
      onUpdate({
        type: 'status_update',
        timestamp: Date.now()
      })
    }, 5000)
  }
  
  const stop = () => {
    if (intervalId) {
      clearInterval(intervalId)
    }
  }
  
  return { start, stop }
}

export type { Station }